package top.leyi.handle;

import org.springframework.boot.web.servlet.server.Session;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
import top.leyi.entity.user.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RequestMapping("/api/view")
@Controller
@SessionAttributes("role")
public class ViewHandle {

     @ModelAttribute
     public void pre(HttpSession session){


     }

     @RequestMapping("/login")
     public ModelAndView pageLogin(){
         ModelAndView mv = new ModelAndView("admin/login.html");
         return mv;
     }


     @GetMapping("/index")
     public ModelAndView doIndex(HttpServletRequest request, HttpSession session,Model model){

         String username = request.getParameter("username");
         String password = request.getParameter("password");
         boolean isLogin = (username != null || password != null);

         ModelAndView mv;
         if(((session.getAttribute("role") != null)) ||
                 ("admin".equals(username) && "admin".equals(password) )
           ) {
             mv = new ModelAndView("index.html");
             mv.addObject("role","admin");
         }
         else {
             mv = new ModelAndView("admin/login.html");
             if(!isLogin)
                 model.addAttribute("msg","Cookie已失效，请先登录后进行操作");
             else {
                 model.addAttribute("msg","用户名或密码错误");
             }
         }
         return mv;
     }

    @GetMapping("/logOut")
    public ModelAndView doLogOut(HttpServletRequest request,SessionStatus sessionStatus,  HttpSession session){


        sessionStatus.setComplete();
        return pageLogin();
    }
}
